package com.example.taskschedule;

import com.example.taskschedule.application.task.TaskSubmitter;
import com.example.taskschedule.infrastructure.monitor.ThreadPoolMonitor;
import com.example.taskschedule.infrastructure.threadPool.CustomRejectedExecutionHandler;
import com.example.taskschedule.infrastructure.threadPool.CustomThreadFactory;
import com.example.taskschedule.infrastructure.threadPool.StatisticsCollector;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class TaskScheduleApplication {
    //线程池配置参数
    private static final int CORE_POOL_SIZE=4;
    private static final int MAX_POOL_SIZE=10;
    private static final int QUEUE_CAPACITY=50;
    private static final int TASKS_PER_SECOND=10;
    private static final int SUBMISSION_DURATION_SECONDS=30;
    public static void main(String[] args) {
        try {
            //创建自定义线程工厂
            CustomThreadFactory customThreadFactory = new CustomThreadFactory("my-thread");
            //创建自定义拒绝策略
            CustomRejectedExecutionHandler customRejectedHandler = new CustomRejectedExecutionHandler();
            ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                    CORE_POOL_SIZE,
                    MAX_POOL_SIZE,
                    60L,
                    TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(QUEUE_CAPACITY),
                    customThreadFactory,
                    customRejectedHandler
            );
            //启动监控线程
            Thread monitorThread = new Thread(new ThreadPoolMonitor(threadPool));
            monitorThread.setDaemon(true);
            monitorThread.start();
            //提交任务
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            scheduler.scheduleAtFixedRate(new TaskSubmitter(threadPool, TASKS_PER_SECOND),0,1,TimeUnit.SECONDS);
            Thread.sleep((SUBMISSION_DURATION_SECONDS+1)*1000L);
            //提交三十秒
            scheduler.shutdown();
            //关闭线程池,允许已提交的任务执行完毕，但不接受新的任务
            threadPool.shutdown();
            
            // 等待所有任务完成
            if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
                log.warn("线程池在等待时间内未完全终止");
            }
            
            // 中断监控线程
            monitorThread.interrupt();
            
            // 打印统计结果
            StatisticsCollector.printStatistics();
            
        } catch (Exception e) {
            log.error("error: {}", e.getMessage(), e);
        }

    }

}
